import { defineComponent, onMounted, shallowRef, useTemplateRef } from 'vue'
import * as Cesium from 'cesium'
import DataLayerCollection from './dataLayerCollection/index.vue'
import parseAPNG from 'apng-js'

export default defineComponent({
  setup() {
    const domRef = useTemplateRef<HTMLDivElement>('dom')
    const viewer = shallowRef<Cesium.Viewer>()
    onMounted(async () => {
      if (!domRef.value) return
      viewer.value = new Cesium.Viewer(domRef.value, {
        navigationHelpButton: false,
        animation: false,
        timeline: false,
        baseLayerPicker: false,
        homeButton: false,
        geocoder: false,
        sceneModePicker: false,
        fullscreenButton: false,
        infoBox: false,
        sceneMode: Cesium.SceneMode.SCENE2D,
      })

      viewer.value.cesiumWidget.creditContainer.style.display = 'none'

      viewer.value.imageryLayers.removeAll()

      const imageryProvider = new Cesium.UrlTemplateImageryProvider({
        url: 'https://webst0{s}.is.autonavi.com/appmaptile?style=7&x={x}&y={y}&z={z}',
        subdomains: ['1', '2', '3', '4'], // 高德地图子域名
        tilingScheme: new Cesium.WebMercatorTilingScheme(), // 高德使用Web墨卡托投影
        minimumLevel: 3,
        maximumLevel: 18,
        credit: new Cesium.Credit('高德地图'),
      })

      viewer.value.imageryLayers.addImageryProvider(imageryProvider)

      // 设置初始视图范围（渝中区）
      const initialRectangle = Cesium.Cartesian3.fromDegrees(106.57, 29.559, 6000)
      viewer.value.camera.setView({ destination: initialRectangle })

      // 加载apng动图
      const loadApngImg = async () => {
        const blob = await fetch('/public/images/1732092621917.png').then((res) => res.blob())
        const reader = new FileReader()
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        reader.readAsArrayBuffer(blob)
        reader.onload = async () => {
          const apng = parseAPNG(reader.result)
          if (apng instanceof Error || !ctx || !viewer.value) {
            return
          }
          const player = await apng.getPlayer(ctx)
          console.log('🚀 ~ loadApngImg ~ player:', player)
          player.play()
          viewer.value.entities.add({
            position: Cesium.Cartesian3.fromDegrees(106.57, 29.559),
            billboard: {
              image: new Cesium.CallbackProperty(() => {
                return player.currentFrame.imageElement
              }, false),
            },
          })
        }
      }
      loadApngImg()
    })

    return () => (
      <>
        <div ref="dom" style={{ width: '100%', height: '100vh' }}></div>
        {!!viewer.value && <DataLayerCollection viewer={viewer.value} />}
        {/* {!!viewer.value && <Home viewer={viewer.value} />} */}
      </>
    )
  },
})
